package com.leetcode.offer.chapter5;

import java.util.*;

/**
 * @author Dennis Li
 * @date 2020/7/16 16:44
 */
public class LeastKNumbers_40 {

    public int[] getLeastNumbers(int[] arr, int k) {
        if(k == 0) return new int[0];
        // 优先队列
        PriorityQueue<Integer> queue = new PriorityQueue<>((o1, o2) -> o2 - o1);
        for (int i = 0; i < arr.length; i++) {
            if (queue.size() < k) {
                queue.offer(arr[i]);
            }
            else if (queue.peek() > arr[i]) {
                queue.poll();
                queue.offer(arr[i]);
            }
        }
        int[] ans = new int[k];
        int index = 0;
        for (int integer : queue) {
            ans[index++] = integer;
        }
        return ans;
    }

    public int[] getLeastNumbers2(int[] arr, int k) {
        // 排序
        Arrays.sort(arr);
        int[] ans = new int[k];
        for (int i = 0; i < k; i++) {
            ans[i] = arr[i];
        }
        return ans;
    }

}
